//! # 性能优化模块
//! 
//! 提供连接池、内存管理、异步优化等性能优化功能，采用面向接口编程设计。
//! 支持多种后端实现和灵活的配置管理，专注于微服务架构下的高性能需求。
//! 
//! ## 核心组件
//! 
//! - **traits**: 性能管理核心接口定义
//! - **connection**: 连接池管理实现
//! - **memory**: 内存管理器实现
//! - **async_pool**: 异步任务池实现
//! - **config**: 性能配置管理
//! 
//! ## 快速开始
//! 
//! ```rust
//! use rustcloud::performance::{ConnectionPool, ConnectionPoolBuilder, MemoryManager};
//! 
//! // 创建连接池
//! let pool = ConnectionPoolBuilder::new()
//!     .max_connections(100)
//!     .build();
//! 
//! // 初始化连接池
//! pool.initialize().await?;
//! 
//! // 获取连接
//! let connection = pool.acquire().await?;
//! 
//! // 使用连接...
//! 
//! // 释放连接
//! pool.release(&connection.id).await?;
//! ```

pub mod traits;
pub mod connection;
pub mod memory;
pub mod async_pool;
pub mod config;

#[cfg(test)]
pub mod tests;

// 重新导出主要类型和函数
pub use traits::{
    ConnectionPool,
    ConnectionFactory,
    MemoryManager,
    AsyncTaskPool,
    PooledConnection,
    PoolStats,
    MemoryStats,
    TaskStats,
    ConnectionState,
};

pub use connection::{
    GenericConnectionPool,
    ConnectionPoolConfig,
    ConnectionPoolBuilder,
};

pub use memory::{
    MemoryManagerImpl,
    MemoryPool,
    GcConfig,
    MemoryManagerBuilder,
};

pub use async_pool::{
    AsyncTaskPoolImpl,
    AsyncTaskPoolBuilder,
    create_default_async_pool,
    create_async_pool_with_workers,
};

pub use config::{
    PerformanceConfig,
    ConnectionPoolConfig as ConfigConnectionPoolConfig,
    ThreadPoolConfig,
    MemoryConfig,
    GcConfig as ConfigGcConfig,
    AsyncTaskPoolConfig,
    PerformanceConfigBuilder,
};

/// 便捷宏：创建连接池
/// 
/// # 使用示例
/// 
/// ```rust
/// use rustcloud::performance::*;
/// 
/// // 创建连接池
/// let pool = create_connection_pool!(MyConnectionFactory, max_connections: 100, min_connections: 10);
/// ```
#[macro_export]
macro_rules! create_connection_pool {
    ($factory:expr, max_connections: $max:expr, min_connections: $min:expr) => {
        {
            use $crate::performance::connection::ConnectionPoolBuilder;
            ConnectionPoolBuilder::new()
                .max_connections($max)
                .min_connections($min)
                .with_factory($factory)
                .build()
                .expect("Failed to build connection pool")
        }
    };
}

/// 便捷宏：创建内存管理器
/// 
/// # 使用示例
/// 
/// ```rust
/// use rustcloud::performance::*;
/// 
/// // 创建内存管理器
/// let memory_manager = create_memory_manager!(auto_gc: true, gc_threshold: 0.8);
/// ```
#[macro_export]
macro_rules! create_memory_manager {
    (auto_gc: $auto_gc:expr, gc_threshold: $threshold:expr) => {
        {
            use $crate::performance::memory::MemoryManagerBuilder;
            MemoryManagerBuilder::new()
                .auto_gc_enabled($auto_gc)
                .gc_threshold($threshold)
                .build()
        }
    };
}

/// 便捷宏：创建异步任务池
/// 
/// # 使用示例
/// 
/// ```rust
/// use rustcloud::performance::*;
/// 
/// // 创建异步任务池
/// let async_pool = create_async_task_pool!(worker_threads: 8);
/// ```
#[macro_export]
macro_rules! create_async_task_pool {
    (worker_threads: $workers:expr) => {
        {
            use $crate::performance::async_pool::AsyncTaskPoolBuilder;
            AsyncTaskPoolBuilder::new()
                .worker_count($workers)
                .build()
        }
    };
}

/// 创建默认性能配置
/// 
/// 使用系统默认值创建性能配置。
/// 
/// # 返回值
/// 
/// 默认的性能配置实例
pub fn create_default_performance_config() -> PerformanceConfig {
    PerformanceConfig::default()
}

/// 创建连接池工厂
/// 
/// 根据配置创建连接池实例。
/// 
/// # 参数
/// 
/// * `config` - 连接池配置
/// * `factory` - 连接工厂实现
/// 
/// # 返回值
/// 
/// 配置好的连接池实例
pub fn create_connection_pool_with_config<T: Send + Sync + 'static>(
    config: ConnectionPoolConfig,
    factory: std::sync::Arc<dyn ConnectionFactory<T>>,
) -> GenericConnectionPool<T> {
    GenericConnectionPool::new(config, factory)
}

/// 创建内存管理器工厂
/// 
/// 根据配置创建内存管理器实例。
/// 
/// # 参数
/// 
/// * `config` - 内存配置
/// 
/// # 返回值
/// 
/// 配置好的内存管理器实例
pub fn create_memory_manager_with_config(config: MemoryConfig) -> MemoryManagerImpl {
    let gc_config = config.gc;
    MemoryManagerBuilder::new()
        .auto_gc_enabled(gc_config.auto_gc_enabled)
        .gc_threshold(gc_config.gc_threshold)
        .gc_interval(gc_config.gc_interval())
        .pressure_threshold(gc_config.pressure_threshold)
        .build()
}

/// 创建异步任务池工厂
/// 
/// 根据配置创建异步任务池实例。
/// 
/// # 参数
/// 
/// * `config` - 异步任务池配置
/// 
/// # 返回值
/// 
/// 配置好的异步任务池实例
pub fn create_async_pool_with_config(config: AsyncTaskPoolConfig) -> AsyncTaskPoolImpl {
    AsyncTaskPoolBuilder::new()
        .worker_count(config.worker_threads)
        .build()
}

/// 性能管理器
/// 
/// 统一管理所有性能优化组件的高层抽象。
pub struct PerformanceManager {
    /// 连接池
    pub connection_pool: Option<std::sync::Arc<dyn ConnectionPool<()>>>,
    
    /// 内存管理器
    pub memory_manager: Option<std::sync::Arc<dyn MemoryManager>>,
    
    /// 异步任务池
    pub async_task_pool: Option<std::sync::Arc<dyn AsyncTaskPool>>,
}

impl PerformanceManager {
    /// 创建新的性能管理器
    pub fn new() -> Self {
        Self {
            connection_pool: None,
            memory_manager: None,
            async_task_pool: None,
        }
    }

    /// 设置连接池
    pub fn with_connection_pool<T: Send + Sync + 'static>(
        mut self,
        pool: std::sync::Arc<dyn ConnectionPool<T>>,
    ) -> Self {
        // 注意：这里我们进行了类型擦除，将具体类型转换为()
        // 在实际使用中，需要确保类型匹配
        self.connection_pool = Some(pool as std::sync::Arc<dyn ConnectionPool<()>>);
        self
    }

    /// 设置内存管理器
    pub fn with_memory_manager(mut self, manager: std::sync::Arc<dyn MemoryManager>) -> Self {
        self.memory_manager = Some(manager);
        self
    }

    /// 设置异步任务池
    pub fn with_async_task_pool(mut self, pool: std::sync::Arc<dyn AsyncTaskPool>) -> Self {
        self.async_task_pool = Some(pool);
        self
    }

    /// 获取连接池统计信息
    pub async fn get_connection_pool_stats(&self) -> Option<PoolStats> {
        if let Some(ref pool) = self.connection_pool {
            Some(pool.get_stats().await)
        } else {
            None
        }
    }

    /// 获取内存统计信息
    pub async fn get_memory_stats(&self) -> Option<MemoryStats> {
        if let Some(ref manager) = self.memory_manager {
            Some(manager.get_stats().await)
        } else {
            None
        }
    }

    /// 获取异步任务池统计信息
    pub async fn get_async_pool_stats(&self) -> Option<TaskStats> {
        if let Some(ref pool) = self.async_task_pool {
            Some(pool.get_stats().await)
        } else {
            None
        }
    }

    /// 关闭所有性能组件
    pub async fn shutdown(&self) -> rustcloud_core::ServiceResult<()> {
        if let Some(ref pool) = self.connection_pool {
            pool.shutdown().await?;
        }
        
        if let Some(ref manager) = self.memory_manager {
            // 内存管理器没有shutdown方法，但我们可以执行一次GC
            let _ = manager.garbage_collect().await;
        }
        
        if let Some(ref pool) = self.async_task_pool {
            pool.shutdown().await?;
        }
        
        Ok(())
    }
}

impl Default for PerformanceManager {
    fn default() -> Self {
        Self::new()
    }
}

/// 性能管理器构建器
pub struct PerformanceManagerBuilder {
    manager: PerformanceManager,
}

impl PerformanceManagerBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            manager: PerformanceManager::new(),
        }
    }

    /// 设置连接池
    pub fn with_connection_pool<T: Send + Sync + 'static>(
        mut self,
        pool: std::sync::Arc<dyn ConnectionPool<T>>,
    ) -> Self {
        self.manager = self.manager.with_connection_pool(pool);
        self
    }

    /// 设置内存管理器
    pub fn with_memory_manager(mut self, manager: std::sync::Arc<dyn MemoryManager>) -> Self {
        self.manager = self.manager.with_memory_manager(manager);
        self
    }

    /// 设置异步任务池
    pub fn with_async_task_pool(mut self, pool: std::sync::Arc<dyn AsyncTaskPool>) -> Self {
        self.manager = self.manager.with_async_task_pool(pool);
        self
    }

    /// 构建性能管理器
    pub fn build(self) -> PerformanceManager {
        self.manager
    }
}

impl Default for PerformanceManagerBuilder {
    fn default() -> Self {
        Self::new()
    }
}